#include "cJSON/cJSON.h"
#include "log/log.h"
#include "unistd.h"
#include "string.h"

void parse_json(void)
{
    char *json = "{\"name\": \"lisi\", \"age\": 18, \"sex\": \"male\"}";

    cJSON *root = cJSON_Parse(json);

    if (root == NULL)
    {
        log_error("parse json error");
        return;
    }
    cJSON *nameItem = cJSON_GetObjectItem(root, "name");
    if (nameItem != NULL)
    {
        char *name = cJSON_GetStringValue(nameItem);
        log_info("name: %s", name);
    }

    cJSON_Delete(root);
}

char *to_json(void)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "name", "zhangsan");
    cJSON_AddNumberToObject(root, "age", 18);
    cJSON_AddBoolToObject(root, "is_married", true);

    // char *str = cJSON_Print(root);
    char *str = cJSON_PrintUnformatted(root);
    // log_info("json: %s", str);
    char *dup = strdup(str);  // 字符串的深copy
    cJSON_Delete(root);
    sleep(2);
    return dup;
}

int main(int argc, char const *argv[])
{
    // parse_json();
    char *str = to_json();
    log_info("json: %s", str);
    return 0;
}
